package com.hospital.rank.module.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 * @author yhn
 * @version 1.0
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // ====================== String ======================

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public boolean setIfAbsent(String key, Object value, long timeout, TimeUnit unit) {
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, value, timeout, unit));
    }

    // ====================== Hash ======================

    public void hSet(String key, String field, Object value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    public Object hGet(String key, String field) {
        return redisTemplate.opsForHash().get(key, field);
    }

    public Map<Object, Object> hGetAll(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    public void hDel(String key, String... fields) {
        redisTemplate.opsForHash().delete(key, (Object[]) fields);
    }

    // ====================== List ======================

    public void lPush(String key, Object value) {
        redisTemplate.opsForList().leftPush(key, value);
    }

    public Object lPop(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }

    public List<Object> lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    // ====================== Set ======================

    public void sAdd(String key, Object... values) {
        redisTemplate.opsForSet().add(key, values);
    }

    public Set<Object> sMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    public boolean sIsMember(String key, Object value) {
        return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, value));
    }

    // ====================== ZSet ======================

    public void zAdd(String key, Object value, double score) {
        redisTemplate.opsForZSet().add(key, value, score);
    }

    public Set<Object> zRange(String key, long start, long end) {
        return redisTemplate.opsForZSet().range(key, start, end);
    }
    /**
     * 获取排行榜前 N 名（分数从高到低）
     * @param key Redis ZSet 键名
     * @param topN 前 N 名
     * @return Map<成员, 分数>，按排名顺序
     */
    public Map<Object, Object> getTopN(String key, int topN) {
        Set<ZSetOperations.TypedTuple<Object>> result = redisTemplate.opsForZSet()
                .reverseRangeWithScores(key, 0, topN - 1);

        if (result == null || result.isEmpty()) {
            return Collections.emptyMap();
        }

        // 保证顺序：LinkedHashMap
        Map<Object, Object> ranking = new LinkedHashMap<>();
        for (ZSetOperations.TypedTuple<Object> tuple : result) {
            ranking.put(tuple.getValue(), tuple.getScore());
        }
        return ranking;
    }

    // ====================== 通用操作 ======================

    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public void del(String... keys) {
        redisTemplate.delete(Arrays.asList(keys));
    }

    public boolean expire(String key, long timeout, TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    public long getExpire(String key, TimeUnit unit) {
        return redisTemplate.getExpire(key, unit);
    }

    /**
     * 尝试设置一个键，如果不存在则设置成功（SETNX）
     * @param key Redis键
     * @param value 值（可设置为唯一标识或时间戳）
     * @param expireSeconds 过期时间（秒）
     * @return true 表示设置成功；false 表示键已存在
     */
    public boolean trySetNx(String key, String value, long expireSeconds, TimeUnit timeUnit) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        Boolean success = ops.setIfAbsent(key, value, expireSeconds, timeUnit);
        return Boolean.TRUE.equals(success);
    }
}

